package com.fantabest.common.client.widget;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.GridEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TabPanelEvent;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.fantabest.common.client.ColumnModelManager;
import com.fantabest.common.client.FantaBestConstants;
import com.fantabest.common.client.RegistryKeys;
import com.fantabest.common.client.StoreManager;

public class PlayersPanel extends TabPanel {

	private FantaBestConstants constants = Registry.get(RegistryKeys.CONSTANTS);
	private TabItem goalkeepersTab;
	private TabItem defendersTab;
	private TabItem midfieldersTab;
	private TabItem forwardsTab;

	public PlayersPanel() {
		super();
		initUI();
	}

	private void initUI() {
		this.setHeight(300);
		this.addListener(Events.Select, new Listener<BaseEvent>() {

			public void handleEvent(BaseEvent be) {
				TabPanelEvent evt = (TabPanelEvent) be;
				TabItem item = evt.getItem();
				if (!(item.getItemCount() > 0)) {
					item.add(createGrid(item.getItemId()));
					item.layout(true);
				}
			}
		});

		goalkeepersTab = new TabItem(constants.goalkeepers());
		goalkeepersTab.setItemId("P");
		goalkeepersTab.setLayout(new FitLayout());
		goalkeepersTab.add(createGrid("P"));

		defendersTab = new TabItem(constants.defenders());
		defendersTab.setItemId("D");
		defendersTab.setLayout(new FitLayout());
		// defendersTab.add(createGrid("D"));

		midfieldersTab = new TabItem(constants.midfielders());
		midfieldersTab.setItemId("C");
		midfieldersTab.setLayout(new FitLayout());
		// midfieldersTab.add(createGrid("C"));

		forwardsTab = new TabItem(constants.forwards());
		forwardsTab.setItemId("A");
		forwardsTab.setLayout(new FitLayout());
		// forwardsTab.add(createGrid("A"));

		this.add(goalkeepersTab);
		this.add(defendersTab);
		this.add(midfieldersTab);
		this.add(forwardsTab);
	}

	protected Grid<BeanModel> createGrid(String position) {
		final Grid<BeanModel> grid = new Grid<BeanModel>(StoreManager
				.getInstance().getPlayersStore(position), ColumnModelManager
				.getInstance().getPlayersCM());
		grid.setAutoExpandColumn("lastname");
		grid.setLoadMask(true);
		grid.addListener(Events.Attach, new Listener<GridEvent<BeanModel>>() {
			public void handleEvent(GridEvent<BeanModel> be) {
				grid.getStore().getLoader().load();
			}
		});
		grid.setHeight(300);
		return grid;
	}

}
